package com.example.demo.controller;

import com.example.demo.config.SiteConfig;
import com.example.demo.domain.Filedata;
import com.example.demo.service.FiledataService;
import com.example.demo.util.FileChange;
import com.example.demo.util.MD5Util;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

@Controller
public class FileController {
    @GetMapping("/test")
    @ResponseBody
    public void test() {
//        String[] allowFileType = new String[]{"jpeg","jpg","png","gif","ico"};
//        System.out.println(Arrays.asList(allowFileType).contains("jpg"));
//        System.out.println(Arrays.asList(allowFileType).contains("jp"));
//        UUID uuid = UUID.randomUUID();
//        return uuid.toString().replace("-", "");
    }

    @GetMapping("/")
    public String uppage() {
        return "uppage";
    }

    //todo 将配置放入配置项中
//    private static String UPLOAD_PATH = "/file/image/upload"; //使用此项会在磁盘根目录创建
//    private static String UPLOAD_PATH = "file/image/upload";    //使用此项会在项目同级目录创建
    private static float THUMB_SCAN = 0.5f;
    private static String[] ALLOW_TYPE = new String[]{".jpeg",".jpg",".png",".gif",".ico"};

    @Autowired
    private FiledataService filedataService;

    @Autowired
    private SiteConfig siteConfig;

    @RequestMapping(value = "/upload",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return "file is empty";
        }
        try {
            String md5 = FileChange.getMd5(multipartFile);
            System.out.println(md5);
            Filedata hasSaved = filedataService.getFiledataByFilehash(md5);
            if(hasSaved != null){
                return "文件已存在，地址为: "+hasSaved.getFileurl() +" 缩略图地址为: " +hasSaved.getFilethumb();
            }
            String filename = multipartFile.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String name = uuid + filename.substring(filename.lastIndexOf("."));
            InputStream inputStream = multipartFile.getInputStream();
            Path dir = Paths.get(siteConfig.getUpload_path());
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            }
            try {
                long copy = Files.copy(inputStream, dir.resolve(name));
                Date date = new Date();
                String ext =  filename.substring(filename.lastIndexOf("."));    //带.的文件后缀

                Filedata filedata = new Filedata();
                filedata.setUserid(100L);
                filedata.setFilename(name);
                filedata.setFilehash(md5);
                filedata.setFileurl(siteConfig.getUrl() + siteConfig.getUpload_path() + "/" + name);

                if(Arrays.asList(ALLOW_TYPE).contains(ext) == true){
                    String thumbPath = uuid + "_thumb" + ext;
                    Thumbnails.of(siteConfig.getUpload_path() + "/" + name).scale(THUMB_SCAN).toFile(siteConfig.getUpload_path() + "/" + thumbPath);
                    filedata.setFilethumb(siteConfig.getUrl() + siteConfig.getUpload_path() + "/" + thumbPath);
                }

                filedata.setSize((int) (multipartFile.getSize() / 1024));
                filedata.setCreated_at(date);
                filedataService.saveFiledata(filedata);

                return "上传成功，大小:" + copy / 1024 + "KB,文件MD5：" + md5;
            } catch (Exception e) {
                return e.getMessage() + " 文件已存在，MD5：" + md5;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    //使用流将图片输出
    @GetMapping("/show/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        response.setHeader("Content-Disposition", "inline; filename=girls.png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(siteConfig.getUpload_path()).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping("/upload_nouse")
    @ResponseBody
    public String upload2(@RequestParam("file") MultipartFile multipartFile) {   //此方法存在路径问题
        if (multipartFile.isEmpty()) {
            return "file is empty";
        }
        String filename = multipartFile.getOriginalFilename();
        System.out.println("filename is : " + filename);
        String newFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 6) + filename;
        File file = null;
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println("path is :" + path);
            File upload = new File(path.getAbsolutePath(), "static/tmpupload/");
            System.out.println("upload is :" + upload);
            if (!upload.exists()) upload.mkdirs();
            String uploadPath = upload + "\\";
            file = new File(uploadPath + newFileName);
            multipartFile.transferTo(file);
            System.out.println("file is :" + file);

            String fileMD5 = MD5Util.getFileMD5(file);
            System.out.println("file MD5 is :" + fileMD5);
        } catch (Exception e) {
            return "file upload err :" + e.getMessage();
        } finally {
            try {
//                file.delete();
            } catch (Exception e) {
                //todo
            }
        }
        return newFileName;
    }
}
